class HumansController < ApplicationController
  before_filter :login_required
  
  def new
    @page_title = I18n.t('human.new_title')
    @human = Human.new
    @human_photo = Photo.new
    render :action => 'form'
  end
  
  def create
    @page_title = I18n.t('human.new_title')    
    @human = Human.new(:user => current_user)    
    @human.attributes = params[:human] if params[:human]
    @human.colors = "234243"
    @human.save if (success = @human && @human.valid?)
    if success && @human.errors.empty? 
      if params[:ajax].to_s == "true"
        render :text => @human.id.to_s + "<br />" + @human.name
      else
        redirect_to "/" + @human.alias
      end      
    else     
      if params[:ajax].to_s == "true"
        render :inline => "<%= error_messages_for :human %>"  
      else
        @human_photo = Photo.new      
         render :action => 'form'
      end      
    end
  end

  def edit    
    @page_title = I18n.t('human.edit_title')
    @human = Human.find(:first, :conditions => ["id = ?", params[:id]])    
    @human_photo = Photo.new
    if @human and @human.is_rewritable(current_user)
      render :action => 'form'
    else
      redirect_back_or_default('/')
    end
  end

  def update
    @page_title = I18n.t('human.edit_title')    
    @human = Human.find(:first, :conditions => ["id = ?", params[:id]])
    if @human and @human.is_rewritable(current_user)      
      @human.attributes = params[:human]    
      @human.save if (success = @human && @human.valid?)    
      if success && @human.errors.empty?
        redirect_to "/" + @human.alias
      else 
        @human_photo = Photo.new
        render :action => 'form'
      end
    else
      redirect_to "/" + @human.alias
    end
  end

  def exist
    humans = ""
    if params[:name].to_s != ""
      names = Human.find(:all, 
                            :conditions => ["name like ? ", "%" + params[:name] + "%"], :limit => 12)
      names.each { |i| humans += "<a href='/#{i.alias}'>" + i.name + "</a><br />" }
    end
    render :text => humans
  end
  
  def auto_complete_for_name
    humans = ""    
    if params[:q].to_s != ""
      q = ""      
      params[:q].split(" ").each { |i|  q += " name like '%#{i}%' OR " }
      q = q[0, q.length - 4]
      names = Human.find(:all, :conditions => q + 
          (params[:human_ids].blank? ? "" : " AND id NOT IN (#{params[:human_ids]})"), :limit => 20)
      names.each { |i| humans += i.name + "|" + i.id.to_s + "|" + i.name + "\n" }
    end
    humans += "Clicca per aggiungere #{params[:q]} se non compare nella lista |0|#{params[:q]}\n"
    
    render :text => humans
  end
  
  def get_form
    new
  end
end
